﻿#region Using

using PMSystem.ApplicationLogics;
using PMSystem.DataAccess;
using PMSystem.DataAccess.DataRepository;
using PMSytem.Windows.App;
using PMSytem.Windows.App.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

#endregion Using

namespace PMSytem.Windows.Tests
{
    public class RecordItemsDataSourceX:RecordItem
    {
        public bool IsHasEditPermission { get { return LoginUser.IsUserHasEditPermission;} }
    }
    #region class ColorChooser

    public partial class SearchWindow : ToolWindow
    {

        private ObservableCollection<RecordItem> datasource =
        new ObservableCollection<RecordItem>();
        RecordItemService _service;
        AuditManager _audit;

        private int currentRecordid = 0;

        #region Constructor

        public SearchWindow()
        {
            InitializeComponent();
            DataContext = this;
            _service = new RecordItemService();
            _audit = new AuditManager();
        }

       

        #endregion Constructor

        public bool HasPermissions
        {
            get { return LoginUser.IsUserHasEditPermission; }
        }

        #region btnSearch_Click

        public ObservableCollection<RecordItem> RecordItemCollection
        {
            get
            {
                return datasource;
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            datasource.Clear();
            try
            {
                var results = _service.GetRecordsBySearch(txtSearch.Text);

                if (results.Count > 0)
                {
                    foreach (var item in results)
                    {
                        //var recrd = new RecordItemsDataSource(){}
                        datasource.Add(item);
                    }
                }else
                {
                    MessageBox.Show("No search result found.",
                           "Search Result",
                            MessageBoxButton.OK,
                           MessageBoxImage.Information,
                            MessageBoxResult.OK, null);
                }

            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

        #endregion btnSearch_Click



        private void lnkviewPhoto_Click(object sender, RoutedEventArgs e)
        {
            var obj = sender as Hyperlink;
            if(obj!=null)
            {
                var id = obj.CommandParameter;
                var command = obj.TargetName.ToString();
                currentRecordid = (int)id;
                switch (command)
                {
                    case "viewrecord":
                        AuditManager.AddAuditRecord(AuditEntity.ViewRecord, "view the record item( record id:" + currentRecordid + ")");
                        ViewRecord view = new ViewRecord(currentRecordid);
                        view.Header = "View Record";
                        view.Parent = this.Parent;
                        view.StartPosition = ToolWindowStartPosition.CenterParent;
                        view.Show();
                        break;
                    case "viewphotos":
                        AuditManager.AddAuditRecord(AuditEntity.ViewRecord, "view the record item photos( record id:" + currentRecordid + ")");
                         ViewPhotos window = new ViewPhotos(currentRecordid);
                         window.Header = "View Record Photos";
                        window.Parent = this.Parent;
                        window.StartPosition = ToolWindowStartPosition.CenterParent;
                        window.Show();
                        break;
                    case "updaterecord": 
                        ViewRecord edit = new ViewRecord(currentRecordid);
                        edit.Header = "Edit Record";
                        edit.Parent = this.Parent;
                        edit.StartPosition = ToolWindowStartPosition.CenterParent;
                        edit.Show();
                        break;
                    case "deleterecord":                      
                        MessageBox.Show("Do you really want to delete this record", 
                           "Record Delete Confirmation",
                            MessageBoxButton.YesNo,
                           MessageBoxImage.Question,
                            MessageBoxResult.OK,
                           new MessageBox.DialogResultEventHandler(this.DialogResult));
                        break;

                }

               
            }
        }
        private void DialogResult(MessageBox.MessageBoxResultEventArgs e)
        {
            //this.LeftStatusContent = String.Format("Result of message: {0}", e.MessageResult.ToString());
            if(e.MessageResult.ToString()=="Yes")
            {
                //this.LeftStatusContent = "sucessfully deleted.";
                new RecordItemService().DeleteRecord(currentRecordid);
                AuditManager.AddAuditRecord(AuditEntity.DeleteRecord, "delete a record item( record id:" + currentRecordid + ")");
            }
        }
      

        
    }

    #endregion class ColorChooser

    public class GridViewSort
    {
        #region Attached properties

        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        // Using a DependencyProperty as the backing store for Command.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached(
                "Command",
                typeof(ICommand),
                typeof(GridViewSort),
                new UIPropertyMetadata(
                    null,
                    (o, e) =>
                    {
                        ItemsControl listView = o as ItemsControl;
                        if (listView != null)
                        {
                            if (!GetAutoSort(listView)) // Don't change click handler if AutoSort enabled
                            {
                                if (e.OldValue != null && e.NewValue == null)
                                {
                                    listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                                if (e.OldValue == null && e.NewValue != null)
                                {
                                    listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                            }
                        }
                    }
                )
            );

        public static bool GetAutoSort(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoSortProperty);
        }

        public static void SetAutoSort(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoSortProperty, value);
        }

        // Using a DependencyProperty as the backing store for AutoSort.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AutoSortProperty =
            DependencyProperty.RegisterAttached(
                "AutoSort",
                typeof(bool),
                typeof(GridViewSort),
                new UIPropertyMetadata(
                    false,
                    (o, e) =>
                    {
                        ListView listView = o as ListView;
                        if (listView != null)
                        {
                            if (GetCommand(listView) == null) // Don't change click handler if a command is set
                            {
                                bool oldValue = (bool)e.OldValue;
                                bool newValue = (bool)e.NewValue;
                                if (oldValue && !newValue)
                                {
                                    listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                                if (!oldValue && newValue)
                                {
                                    listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                            }
                        }
                    }
                )
            );

        public static string GetPropertyName(DependencyObject obj)
        {
            return (string)obj.GetValue(PropertyNameProperty);
        }

        public static void SetPropertyName(DependencyObject obj, string value)
        {
            obj.SetValue(PropertyNameProperty, value);
        }

        // Using a DependencyProperty as the backing store for PropertyName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PropertyNameProperty =
            DependencyProperty.RegisterAttached(
                "PropertyName",
                typeof(string),
                typeof(GridViewSort),
                new UIPropertyMetadata(null)
            );

        #endregion Attached properties

        #region Column header click event handler

        private static void ColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
            if (headerClicked != null)
            {
                string propertyName = GetPropertyName(headerClicked.Column);
                if (!string.IsNullOrEmpty(propertyName))
                {
                    ListView listView = GetAncestor<ListView>(headerClicked);
                    if (listView != null)
                    {
                        ICommand command = GetCommand(listView);
                        if (command != null)
                        {
                            if (command.CanExecute(propertyName))
                            {
                                command.Execute(propertyName);
                            }
                        }
                        else if (GetAutoSort(listView))
                        {
                            ApplySort(listView.Items, propertyName);
                        }
                    }
                }
            }
        }

        #endregion Column header click event handler

        #region Helper methods

        public static T GetAncestor<T>(DependencyObject reference) where T : DependencyObject
        {
            DependencyObject parent = VisualTreeHelper.GetParent(reference);
            while (!(parent is T))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            if (parent != null)
                return (T)parent;
            else
                return null;
        }

        public static void ApplySort(ICollectionView view, string propertyName)
        {
            ListSortDirection direction = ListSortDirection.Ascending;
            if (view.SortDescriptions.Count > 0)
            {
                SortDescription currentSort = view.SortDescriptions[0];
                if (currentSort.PropertyName == propertyName)
                {
                    if (currentSort.Direction == ListSortDirection.Ascending)
                        direction = ListSortDirection.Descending;
                    else
                        direction = ListSortDirection.Ascending;
                }
                view.SortDescriptions.Clear();
            }
            if (!string.IsNullOrEmpty(propertyName))
            {
                view.SortDescriptions.Add(new SortDescription(propertyName, direction));
            }
        }

        #endregion Helper methods
    }
}